﻿using ExpenseSystem.Common;
using ExpenseSystem.Common.BaseModel;
using ExpenseSystem.Core;
using ExpenseSystem.Core.Authority;
using ExpenseSystem.Core.DataAddOn;
using ExpenseSystem.Fether;
using ExpenseSystem.Lor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ExpenseSystem
{
    public static class NormalControllerHelper
    {
        public static ResponseModel Export<T>(ExpFetcher<T> fetcher,string authKey,Restrain[] restrains) where T : NormalModel, new()
        {
            if (restrains == null)
                restrains = new Restrain[0];
            Limit limit = new Limit(0,10000);
            ResponseModel responseModel = new ResponseModel();
            UserProfile userProfile = Authority.GetUserProfile();
            Authority authority = new Authority();
            if (userProfile == null || !String.IsNullOrEmpty(authKey))
            {
                if (!authority.GetAuthority(authKey))
                {
                    responseModel.Result = Definition.RESP_NOT_AUTH;
                    responseModel.Count = 0;
                    responseModel.Data = null;
                    responseModel.Message = "没有授予对应的权限";
                    return responseModel;
                }
            }
            string message = "";
            int rows = 0;
            IList<T> models = fetcher.List(userProfile.SiteId, OrderBy.GetDefault(), limit, out message, out rows, restrains);
            responseModel.Count = rows;
            responseModel.Result = Definition.RESP_SUCCESS;
            responseModel.Message = message;
            responseModel.Data = JsonHelper.ArrayToJsonForExport(models);
            return responseModel;
        }
        public static ResponseModel List<T>(NormalFetcher<T> fetcher, string authKey, Restrain[] restrains, Limit limit,GetInhibition inhibition) where T : NormalModel, new()
        {
            if (restrains == null)
                restrains = new Restrain[0];
            if(limit==null)
                limit = new Limit();
            ResponseModel responseModel = new ResponseModel();
            UserProfile userProfile = Authority.GetUserProfile();
            Authority authority = new Authority();
            if (userProfile == null || !String.IsNullOrEmpty(authKey))
            {
                if (!authority.GetAuthority(authKey))
                {
                    responseModel.Result = Definition.RESP_NOT_AUTH;
                    responseModel.Count = 0;
                    responseModel.Data = null;
                    responseModel.Message = "没有授予对应的权限";
                    return responseModel;
                }
            }
            string message = "";
            int rows = 0;
            IList<T> models = fetcher.List(userProfile.SiteId, OrderBy.GetDefault(), limit, out message, out rows, restrains);
            responseModel.Count = rows;
            responseModel.Result = Definition.RESP_SUCCESS;
            responseModel.Message = message;
            responseModel.Data = JsonHelper.ArrayToJson(models, inhibition);
            return responseModel;
        }

        public static ResponseModel List<T>(NormalFetcher<T> fetcher,string authKey, RequestArgs rags, GetInhibition inhibition) where T:NormalModel,new()
        {
            Restrain[] restrains = ExpenseSystem.Core.Converter.RestainConverter.FromRequestArgs(rags);
            if (restrains == null)
                restrains = new Restrain[0];
            Limit limit = new Limit();
            if(rags!=null)
            {
                limit.Pos = (uint)rags.Pos;
                limit.Size = (uint)rags.Length;
            }
            return List(fetcher,authKey,restrains,limit,inhibition);
        }
        public static ResponseModel Get<T>(NormalFetcher<T> fetcher, string authKey, long id, GetInhibition inhibition) where T : NormalModel, new()
        {
            ResponseModel responseModel = new ResponseModel();
            Authority authority = new Authority();
            UserProfile userProfile = Authority.GetUserProfile();
            if (userProfile == null || !String.IsNullOrEmpty(authKey))
            {
                if (!authority.GetAuthority(authKey))
                {
                    responseModel.Result = Definition.RESP_NOT_AUTH;
                    responseModel.Count = 0;
                    responseModel.Data = null;
                    responseModel.Message = "没有授予对应的权限";
                    return responseModel;
                }
            }
            string message = "";
            T model = fetcher.Get(userProfile.SiteId, id, out message);
            if (model == null)
            {
                responseModel.Count = 0;
                responseModel.Result = Definition.RESP_DATA_NOT_FOUND;
                responseModel.Message = message;
                responseModel.Data = "";
            }
            else
            {
                responseModel.Count = 1;
                responseModel.Result = Definition.RESP_SUCCESS;
                responseModel.Message = message;
                responseModel.Data = JsonHelper.ToJson(model, inhibition);
            }
            return responseModel;
        }

        public static ResponseModel Set<T>(NormalFetcher<T> fetcher, string authKey, T data,INormalManager<T> manager, SetInhibition inhibition,GetInhibition getInhibition,params IAddable<T>[] addable) where T : NormalModel, new()
        {
            UserProfile userProfile = Authority.GetUserProfile();
            ResponseModel response = new ResponseModel();
            if (!SiteSetter.Set(data))
            {
                response.Result = Definition.RESP_LOGIN_FAILD;
                response.Count = 0;
                response.Data = null;
                response.Message = "登录信息有误";
                return response;
            }
            Authority authority = new Authority();
            if (!authority.GetAuthority(authKey))
            {
                response.Result = Definition.RESP_NOT_AUTH;
                response.Count = 0;
                response.Data = null;
                response.Message = "没有授予对应的权限";
                return response;
            }
            MergeHelper mergeHelper = new MergeHelper(inhibition);
            T model = mergeHelper.NormalObjMerge(data, fetcher);
            if(model.PropertyUpdated.Contains("State"))
            {
                response.Result = Definition.RESP_STATE_INCORRECT;
                response.Count = 0;
                response.Data = null;
                response.Message = "无法手工更改单据状态";
                return response;
            }
            if (model.State == 0)
            {
                model.State = Definition.STATE_NORMAL;
            }
            if (model.State != Definition.STATE_NORMAL)
            {
                response.Result = Definition.RESP_STATE_INCORRECT;
                response.Count = 0;
                response.Data = null;
                response.Message = "单据状态不正确";
                return response;
            }
            string message = "";
            bool result = manager.Save(model,  out message, addable);
            if (!result) SqlProvider.CloseTransaction(HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString(), false);
            //model.State = data.State;//保存的model不会有state信息，为了返回正确的state信息到前端，必须再次重新赋值
            if (result)
            {
                response.Result = Definition.RESP_SUCCESS;
                response.Count = 1;
                response.Data = JsonHelper.ToJson(model, getInhibition);
            }
            else
            {
                response.Result = Definition.RESP_SET_DATA_ERROR;
                response.Count = 0;
                response.Data = response.Message = message;
                SqlProvider.CloseTransaction(HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString(), false);
            }
            return response;
        }

        public static ResponseModel Remove<T>(string authKey, T data, INormalManager<T> manager) where T : NormalModel, new()
        {
            ResponseModel response = new ResponseModel();
            Authority authority = new Authority();
            if (!authority.GetAuthority(authKey))
            {
                response.Result = Definition.RESP_NOT_AUTH;
                response.Count = 0;
                response.Data = null;
                response.Message = "没有授予对应的权限";
                return response;
            }
            string message = "";
            if(data.State!=Definition.STATE_NORMAL)
            {
                response.Result = Definition.RESP_STATE_INCORRECT;
                response.Count = 0;
                response.Data = null;
                response.Message = "单据状态不正确";
                return response;
            }
            bool result = manager.Delete(data,  out message);
            if (!result) SqlProvider.CloseTransaction(HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString(), false);
            if (result)
            {
                response.Result = Definition.RESP_SUCCESS;
                response.Count = 1;
                response.Message = message;
            }
            else
            {
                response.Result = Definition.RESP_SET_DATA_ERROR;
                response.Count = 0;
                response.Data = response.Message = message;
                SqlProvider.CloseTransaction(HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString(), false);

            }
            return response;
        }
        public static ResponseModel RemoveById<T>(string authKey,long[] id, INormalManager<T> manager) where T : NormalModel, new()
        {
            ResponseModel responseModel = new ResponseModel();
            Authority authority = new Authority();
            if (!authority.GetAuthority(authKey))
            {
                responseModel.Result = Definition.RESP_NOT_AUTH;
                responseModel.Count = 0;
                responseModel.Data = null;
                responseModel.Message = "没有授予对应的权限";
                return responseModel;
            }
            string message = "";
            bool result = manager.DeleteById(id,  out message);
            if (!result) SqlProvider.CloseTransaction(HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString(), false);
            if (result)
            {
                responseModel.Result = Definition.RESP_SUCCESS;
                responseModel.Count = 1;
                responseModel.Message = message;
            }
            else
            {
                responseModel.Result = Definition.RESP_SET_DATA_ERROR;
                responseModel.Count = 0;
                responseModel.Data = responseModel.Message = message;
                SqlProvider.CloseTransaction(HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString(), false);

            }
            return responseModel;
        }
        public static ResponseModel RemoveWithDetail<T,U>(IDetailFetcher<T> dfetcher,
            string authKey, long mainid, INormalManager<U> manager,INormalManager<T> dmanager)
                where T : NormalModel, new()
                where U : NormalModel, new()
        {
            ResponseModel response = new ResponseModel();
            Authority authority = new Authority();
            if (!authority.GetAuthority(authKey))
            {
                response.Result = Definition.RESP_NOT_AUTH;
                response.Count = 0;
                response.Data = null;
                response.Message = "没有授予对应的权限";
                return response;
            }
            bool result = true;
            int rows;
            IList<T> list = dfetcher.ListByMainId(Authority.GetUserProfile().SiteId, mainid, out string message,out rows);
            foreach(T t in list)
            {
                result = dmanager.Delete(t,out message);
                if(!result)
                {
                    break;
                }
            }
            if(result)
            {
                result = manager.DeleteById(new long[] { mainid},out message);
            }
            if (result)
            {
                response.Result = Definition.RESP_SUCCESS;
                response.Count = 1;
                response.Data = "删除成功";
            }
            else
            {
                response.Result = Definition.RESP_SET_DATA_ERROR;
                response.Count = 0;
                response.Data = response.Message = message;
                SqlProvider.CloseTransaction(HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString(), false);

            }
            return response;
        }
        public static ResponseModel RemoveByMainId<T>(IDetailFetcher<T> dfetcher, string authKey, long mainId, INormalManager<T> manager) where T : NormalModel, new()
        {
            ResponseModel response = new ResponseModel();
            Authority authority = new Authority();
            if (!authority.GetAuthority(authKey))
            {
                response.Result = Definition.RESP_NOT_AUTH;
                response.Count = 0;
                response.Data = null;
                response.Message = "没有授予对应的权限";
                return response;
            }
            bool result = true;
            int rows;
            IList<T> detail = dfetcher.ListByMainId(Authority.GetUserProfile().SiteId, mainId, out string message,out rows);
            foreach(T t in detail)
            {
                result = manager.Delete(t,out message);
                if (!result)
                    break;
            }
            if(result)
            {
                response.Result = Definition.RESP_SUCCESS;
                response.Count = 0;
                response.Data = null;
                response.Message = "操作成功";
            }
            else
            {
                response.Result = Definition.RESP_SET_DATA_ERROR;
                response.Count = 0;
                response.Data = null;
                response.Message = "操作失败:"+message;
                SqlProvider.CloseTransaction(HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString(), false);

            }
            return response;
        }
        public static ResponseModel SetDetail<T>(IDetailFetcher<T> dfetcher, NormalFetcher<T> fetcher, string authKey, RequestModel<T> requestData, INormalManager<T> manager, SetInhibition inhibition) where T : NormalModel, new()
        {
            if (requestData.Data == null)
            {
                return new ResponseModel() { Count = 0, Data = "", Message = "来源数据不正确", Result = Definition.RESP_SET_DATA_ERROR };
            }
            ResponseModel response = new ResponseModel();
            Authority authority = new Authority();
            if (!authority.GetAuthority(authKey))
            {
                response.Result = Definition.RESP_NOT_AUTH;
                response.Count = 0;
                response.Data = null;
                response.Message = "没有授予对应的权限";
                return response;
            }

            foreach (T item in requestData.Data)
            {
                if (!SiteSetter.Set(item))
                {
                    response.Result = Definition.RESP_LOGIN_FAILD;
                    response.Count = 0;
                    response.Data = null;
                    response.Message = "登录信息有误";
                    return response;
                }
            }
            
            MergeHelper mergeHelper = new MergeHelper(inhibition);
            T[] models = new T[requestData.Data.Count()];
            string message = "";
            int rows;
            IList<T> modelsInDB = dfetcher.ListByMainId(Authority.GetUserProfile().SiteId, requestData.MasterId, out message,out rows);

            MyEqualityComparer<T> equalityComparer = new MyEqualityComparer<T>();
            IEnumerable<T> data4Delete = modelsInDB.Except(modelsInDB.Intersect(models, equalityComparer), equalityComparer);
            for (int i = 0; i < requestData.Data.Count(); i++)
            {
                T m = mergeHelper.NormalObjMerge(requestData.Data[i], fetcher);
                if (m.PropertyUpdated.Contains("State"))
                {
                    response.Result = Definition.RESP_STATE_INCORRECT;
                    response.Count = 0;
                    response.Data = null;
                    response.Message = "无法手工更改单据状态";
                    return response;
                }
                models[i] = m;
            }
            bool successed = true;
            foreach (T ru in data4Delete)
            {
                successed = manager.Delete(ru,  out message);
                if (!successed)
                    break;
            }
            if (successed)
            {
                foreach (T ru in models)
                {
                    if(ru.State== 0)
                    {
                        ru.State = Definition.STATE_NORMAL;
                    }
                    if (ru.State != Definition.STATE_NORMAL)
                    {
                        response.Result = Definition.RESP_STATE_INCORRECT;
                        response.Count = 0;
                        response.Data = null;
                        response.Message = "单据状态不正确";
                        successed = false;
                        break;
                    }
                    
                    successed = manager.Save(ru,  out message);
                    if (!successed)
                        break;
                }
            }
            if (!successed) SqlProvider.CloseTransaction(HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString(), false);
            if (successed)
            {
                response.Result = Definition.RESP_SUCCESS;
                response.Count = 1;
                response.Data = JsonHelper.ArrayToJson(models, inhibition);
            }
            else
            {
                response.Result = Definition.RESP_SET_DATA_ERROR;
                response.Count = 0;
                response.Data = response.Message = message;
                SqlProvider.CloseTransaction(HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString(), false);

            }
            return response;
        }
        public static ResponseModel ListDetail<T>(IDetailFetcher<T> fetcher, string authKey, long masterId, GetInhibition inhibition) where T : NormalModel, new()
        {
            ResponseModel responseModel = new ResponseModel();
            Authority authority = new Authority();
            if (!authority.GetAuthority(authKey))
            {
                responseModel.Result = Definition.RESP_NOT_AUTH;
                responseModel.Count = 0;
                responseModel.Data = null;
                responseModel.Message = "没有授予对应的权限";
                return responseModel;
            }
            string message = "";
            int rows;
            IList<T> model = fetcher.ListByMainId(Authority.GetUserProfile().SiteId, masterId, out message,out rows);
            responseModel.Count = rows;
            responseModel.Result = Definition.RESP_SUCCESS;
            responseModel.Message = message;
            responseModel.Data = JsonHelper.ArrayToJson(model, inhibition);
            return responseModel;
        }
        public static ResponseModel Approved<T>(string authKey, long id, IApproveable<T> approver) where T : NormalModel, new()
        {
            ResponseModel responseModel = new ResponseModel();
            Authority authority = new Authority();
            if (!authority.GetAuthority(authKey))
            {
                responseModel.Result = Definition.RESP_NOT_AUTH;
                responseModel.Count = 0;
                responseModel.Data = null;
                responseModel.Message = "没有授予对应的权限";
                return responseModel;
            }
            string message = "";
            bool result = approver.Approved(id, out message);
            if (!result) SqlProvider.CloseTransaction(HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString(), false);
            if (result)
            {
                responseModel.Result = Definition.RESP_SUCCESS;
                responseModel.Count = 1;
                responseModel.Data = "审核成功";
            }
            else
            {
                responseModel.Result = Definition.RESP_SET_DATA_ERROR;
                responseModel.Count = 0;
                responseModel.Data = responseModel.Message = message;
                SqlProvider.CloseTransaction(HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString(), false);

            }
            return responseModel;
        }
        public static ResponseModel Reject<T>(string authKey, long id, IApproveable<T> approver) where T : NormalModel, new()
        {
            ResponseModel responseModel = new ResponseModel();
            Authority authority = new Authority();
            if (!authority.GetAuthority(authKey))
            {
                responseModel.Result = Definition.RESP_NOT_AUTH;
                responseModel.Count = 0;
                responseModel.Data = null;
                responseModel.Message = "没有授予对应的权限";
                return responseModel;
            }
            string message = "";
            bool result = approver.Reject(id, out message);
            if (!result) SqlProvider.CloseTransaction(HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString(), false);
            if (result)
            {
                responseModel.Result = Definition.RESP_SUCCESS;
                responseModel.Count = 1;
                responseModel.Data = "退回成功";
            }
            else
            {
                responseModel.Result = Definition.RESP_SET_DATA_ERROR;
                responseModel.Count = 0;
                responseModel.Data = responseModel.Message = message;
                SqlProvider.CloseTransaction(HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString(), false);

            }
            return responseModel;
        }
        public static ResponseModel Recall<T>(string authKey, long id, IApproveable<T> approver) where T : NormalModel, new()
        {
            ResponseModel responseModel = new ResponseModel();
            Authority authority = new Authority();
            if (!authority.GetAuthority(authKey))
            {
                responseModel.Result = Definition.RESP_NOT_AUTH;
                responseModel.Count = 0;
                responseModel.Data = null;
                responseModel.Message = "没有授予对应的权限";
                return responseModel;
            }
            string message = "";
            bool result = approver.Recall(id, out message);
            if (!result) SqlProvider.CloseTransaction(HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString(), false);
            if (result)
            {
                responseModel.Result = Definition.RESP_SUCCESS;
                responseModel.Count = 1;
                responseModel.Data = "撤回成功";
            }
            else
            {
                responseModel.Result = Definition.RESP_SET_DATA_ERROR;
                responseModel.Count = 0;
                responseModel.Data = responseModel.Message = message;
                SqlProvider.CloseTransaction(HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString(), false);

            }
            return responseModel;
        }
        public static ResponseModel Revert<T>(string authKey, long id, IApproveable<T> approver) where T : NormalModel, new()
        {
            ResponseModel responseModel = new ResponseModel();
            Authority authority = new Authority();
            if (!authority.GetAuthority(authKey))
            {
                responseModel.Result = Definition.RESP_NOT_AUTH;
                responseModel.Count = 0;
                responseModel.Data = null;
                responseModel.Message = "没有授予对应的权限";
                return responseModel;
            }
            string message = "";
            bool result = approver.Revert(id, out message);
            if (!result) SqlProvider.CloseTransaction(HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString(), false);
            if (result)
            {
                responseModel.Result = Definition.RESP_SUCCESS;
                responseModel.Count = 1;
                responseModel.Data = "反审成功";

            }
            else
            {
                responseModel.Result = Definition.RESP_SET_DATA_ERROR;
                responseModel.Count = 0;
                responseModel.Data = responseModel.Message = message;
                SqlProvider.CloseTransaction(HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString(), false);

            }
            return responseModel;
        }
        public static ResponseModel Submit<T>(string authKey, long id, IApproveable<T> approver) where T : NormalModel, new()
        {
            ResponseModel responseModel = new ResponseModel();
            Authority authority = new Authority();
            if (!authority.GetAuthority(authKey))
            {
                responseModel.Result = Definition.RESP_NOT_AUTH;
                responseModel.Count = 0;
                responseModel.Data = null;
                responseModel.Message = "没有授予对应的权限";
                return responseModel;
            }
            string message = "";
            bool result = approver.Submit(id, out message);
            if (!result) SqlProvider.CloseTransaction(HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString(), false);
            if (result)
            {
                responseModel.Result = Definition.RESP_SUCCESS;
                responseModel.Count = 1;
                responseModel.Data = "提交成功";
            }
            else
            {
                responseModel.Result = Definition.RESP_SET_DATA_ERROR;
                responseModel.Count = 0;
                responseModel.Data = responseModel.Message = message;
                SqlProvider.CloseTransaction(HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString(), false);

            }
            return responseModel;
        }

        public static ResponseModel Comfirm<T>(string authKey, long id, IApproveable<T> approver) where T : NormalModel, new()
        {
            ResponseModel responseModel = new ResponseModel();
            Authority authority = new Authority();
            if (!authority.GetAuthority(authKey))
            {
                responseModel.Result = Definition.RESP_NOT_AUTH;
                responseModel.Count = 0;
                responseModel.Data = null;
                responseModel.Message = "没有授予对应的权限";
                return responseModel;
            }
            string message = "";
            bool result = approver.Comfirm(id, out message);
            if (!result) SqlProvider.CloseTransaction(HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString(), false);
            if (result)
            {
                responseModel.Result = Definition.RESP_SUCCESS;
                responseModel.Count = 1;
                responseModel.Data = "确认成功";
            }
            else
            {
                responseModel.Result = Definition.RESP_SET_DATA_ERROR;
                responseModel.Count = 0;
                responseModel.Data = responseModel.Message = message;
                SqlProvider.CloseTransaction(HttpContext.Current.Items[Definition.SESSION_TRAN_STR].ToString(), false);

            }
            return responseModel;
        }
    }
}